//
//  ReleaseView.m
//  releaseInterface
//
//  Created by Gamefire on 16/4/14.
//  Copyright © 2016年 Gamefire. All rights reserved.
//

#import "PostUpLoadImageViewController.h"

#import "CustomcollectionView.h"
#import "Customheadings.h"
#import "scrollView.h"
#import "intputname.h"
#import "refactoring.h"
#import "BottomVIew.h"
#import "WaitingView.h"

#import "Header.h"

#import "DataBaseSaveEditeImageModel.h"
#import "PostUploadImageDataBase.h"



#import "WuLiUpLoadImageRequest.h"
#import "WuLiRequestFlowStar.h"
#import "UserInfoModel.h"

#import "SearchStarViewController.h"


#define  UIColorRGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]

//#define kWindowWidth                        ([[UIScreen mainScreen] bounds].size.width)

#define kWindowHeight                       ([[UIScreen mainScreen] bounds].size.height)


@interface PostUpLoadImageViewController ()<CustomcollectionViewDelegate, inputtextfildDelegate, refactoringDelegate, UIAlertViewDelegate>
{

    CustomcollectionView *collectionview;
    Customheadings *headings;
    scrollView *ScrollView;
    intputname *inte;
    refactoring *refactor;
    UIScrollView *centerBackground;
    UIButton *rightBtn;
    
    NSMutableArray *starListArray;
    NSString *titleString;
    NSString *stringID;
    int reEditeInt;
    
    WaitingView *hudView;
    
    
}


@property (nonatomic, strong) NSMutableArray *totalArray;


@end

@implementation PostUpLoadImageViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:uicolor(237, 237, 237)];
    starListArray = [NSMutableArray new];
    titleString = @"";
    self.totalArray = [NSMutableArray new];
    
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    
    
    
    centerBackground = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, WithView, heightView)];
    [self.view addSubview:centerBackground];

    
    
    
    
    
    [[PostUploadImageDataBase sharedInstance] readAllImageFromDB:^(NSArray *sourceIMageArray, NSArray *postImageArray, NSArray *connectIDArray){
    
        [self.totalArray addObjectsFromArray:sourceIMageArray];
    }];
    
    if (_totalInt <= 4)
    {
        collectionview = [[CustomcollectionView alloc] initWithFrame:CGRectMake(0, 0, WithView, 90)];
        [centerBackground addSubview:collectionview];
        
        ScrollView = [[scrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(collectionview.frame), WithView, 77)];
        [centerBackground addSubview:ScrollView];

    }
    else if (_totalInt >= 5 && _totalInt <= 8)
    {
        collectionview = [[CustomcollectionView alloc] initWithFrame:CGRectMake(0, 0, WithView, 90*2)];
        [centerBackground addSubview:collectionview];
        
        ScrollView = [[scrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(collectionview.frame), WithView, 77)];
        [centerBackground addSubview:ScrollView];

    }
    else
    {
        collectionview = [[CustomcollectionView alloc] initWithFrame:CGRectMake(0, 0, WithView, 270)];
        [centerBackground addSubview:collectionview];
        
        
        ScrollView = [[scrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(collectionview.frame), WithView, 77)];
        [centerBackground addSubview:ScrollView];

    }

    UIImage *image = [UIImage imageNamed:@"gengduomengceng.png"];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(WithView-46, 77-58, 46, 58)];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setTitle:@"更多" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:13.0]];
    [ScrollView addSubview:button];
    [button addTarget:self action:@selector(pushSearchStarVCUpload) forControlEvents:UIControlEventTouchUpInside];
    
    
    inte = [[intputname alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(ScrollView.frame)+9, WithView, 74)];
    [inte setMinputtextfildDelegate:self];
    [centerBackground addSubview:inte];
    
    refactor = [[refactoring alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(inte.frame)+9, WithView,82.5)];
    [refactor setMrefactoringDelegate:self];
    [refactor SelectedEvent];
    [centerBackground addSubview:refactor];

    collectionview.dataArray = self.totalArray;

    
    
    [WuLiRequestFlowStar requestFlowStarWithUserID:[UserInfoModel userIDString]];
    
    
    [centerBackground setContentSize:CGSizeMake(WithView, CGRectGetMaxY(refactor.frame)+160)];
    
    UIButton *bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomBtn setFrame:CGRectMake(0, kWindowHeight - 48.5, WithView,48.5)];
    [bottomBtn setTitle:@"发布" forState:UIControlStateNormal];
    [bottomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:19.0]];
    [bottomBtn setBackgroundColor:UIColorRGBA(255, 205, 5, 1)];
    
    [bottomBtn addTarget:self action:@selector(postUpLoadImage) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:bottomBtn];

    
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WithView, 64.0)];
    [view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:view];
    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 63.5, WithView, 0.5f)];
    [lineView setBackgroundColor:uicolor(102, 102, 102)];
    [self.view addSubview:lineView];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 32.0, WithView, 20.0)];
    [titleLable setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:titleLable];
    [titleLable setText:@"发布"];
    
    
    
    UIImageView *backIMageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 32, 10, 18)];
    [backIMageView setImage:[UIImage imageNamed:@"Detalback.png"]];
    [self.view addSubview:backIMageView];
    
    
    
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    [leftBtn addTarget:self action:@selector(LeftnEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setFrame:CGRectMake(WithView - 45, 25, 45, 34)];
    [rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
    [rightBtn addTarget:self action:@selector(rightEvent:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitleColor:UIColorRGBA(53, 53, 53, 1) forState:UIControlStateNormal];
    [self.view addSubview:rightBtn];
    [rightBtn setSelected:YES];

    
    
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserFloeStarBack:) name:getFloeStar object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getFAbuStarGetBack:) name:@"fabustar" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fabuCenggongGetBack:) name:@"uploadsuccess" object:nil];
    
}



- (void)reloadInputViews
{
    
}



//返回
- (void)LeftnEvent
{
    [[DataBaseSaveEditeImageModel sharedInstance] closeDataBase];
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)getUserFloeStarBack:(NSNotification *)notion
{
    NSDictionary *dic = [notion userInfo];
//    NSLog(@"%@", dic);
    if ([[dic valueForKey:@"success"] intValue] == 1)
    {
        if ([[dic valueForKey:@"data"] count] == 0)
        {
            UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"请关联一位明星" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"关联", nil];
            [alterView show];
        }
        else
        {
            [starListArray removeAllObjects];
            [starListArray addObjectsFromArray:[dic valueForKey:@"data"]];
            //        //        NSLog(@"%@", starListArray);
            //        //        guanzhuScrollView.arrya = starListArray;
            
            [ScrollView.connectView reloadWithArray:[dic valueForKey:@"data"]];

        }
        
        
    }
    else
    {
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    NSLog(@"%d", buttonIndex);
    SearchStarViewController *search = [[SearchStarViewController alloc] init];
    search.starMutableArray = starListArray;
    [self.navigationController pushViewController:search animated:YES];
}



- (void)pushSearchStarVCUpload
{
    SearchStarViewController *search = [[SearchStarViewController alloc] init];
    search.starMutableArray = starListArray;
    [self.navigationController pushViewController:search animated:YES];

}





//编辑
- (void)rightEvent:(UIButton *)sender
{
    if ([sender isSelected])
    {
        [rightBtn setSelected:NO];
        [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
        [collectionview ChangeImage:YES];
    }
    else
    {
        [rightBtn setSelected:YES];
        [rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [collectionview ChangeImage:NO];
    }
}




- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}



- (BOOL)shouldAutorotate
{
    return YES;
}



-(void)keyboardwasShown:(NSNotification *) notify{
//    CGRect frame = [self.view frame];
     NSDictionary *info = [notify userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    
    CGSize keyBoardSize = [aValue CGRectValue].size;
//    [centerBackground setFrame:CGRectMake(0, heightView-keyBoardSize.height-74, WithView, heightView)];
    NSLog(@"%f", CGRectGetMaxY(inte.frame)+68-heightView+keyBoardSize.height);
//    float inputFloat = CGRectGetMaxY(inte.frame)+67;
//    NSLog(@"%f       %f", inputFloat, heightView-keyBoardSize.height);
//    if (inputFloat >heightView - keyBoardSize.height)
//    {
        [centerBackground setFrame:CGRectMake(0, 64-CGRectGetMaxY(inte.frame)-68+heightView-keyBoardSize.height, WithView, heightView)];
//    }
//    else
//    {
//        
//    }
//    NSLog(@"height === %f",keyBoardSize.height);
//    if (keyBoardSize.height >= 224.0) {
//        CGRect rect = centerBackground.frame;
//        rect.origin.y = self.view.frame.size.height - keyBoardSize.height - rect.size.height + 72;
//        centerBackground.frame = rect;
//    }else{
//        CGRect rect = centerBackground.frame;
//        rect.origin.y = self.view.frame.size.height - keyBoardSize.height - rect.size.height + 30;
//        centerBackground.frame = rect;
//    }
}



-(void)keyboardwasHidden:(NSNotification *) notify{
    
    centerBackground.frame = CGRectMake(0, 64, WithView, heightView);
}





//移动照片
- (void)ChangeImageView:(int)canchange
{
    if (canchange == 1)
    {
        [collectionview ChangeImage:YES];
    }
    else
    {
        [collectionview ChangeImage:NO];
    }
}



//编辑完成照片
- (void)changeArrayWithEdite:(NSArray *)endChangeArray
{
    [self.totalArray removeAllObjects];
    [self.totalArray addObjectsFromArray:endChangeArray];
}


//填写标题
- (void)writeTitle:(NSString *)contentString
{
    titleString = contentString;

}



//重构
- (void)changeReEdite:(int)editeInt
{
    reEditeInt = editeInt;
}


//关联明星id
- (void)getFAbuStarGetBack:(NSNotification *)notion
{
    stringID = [notion object];
}






//发布照片
- (void)postUpLoadImage
{
    
    
    if ([titleString length] == 0)
    {
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"请输入标题" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"关联", nil];
        [alterView show];
    }
    else
    {
        
        hudView = [[WaitingView alloc] initWithFrame:CGRectMake(0, 0, WithView, heightView)];
        [hudView setString:@"正在上传"];
        [self.view addSubview:hudView];
        
        NSMutableDictionary *dic = [NSMutableDictionary new];
        
        NSMutableArray *array = [NSMutableArray new];
        
        for (int i = 0; i < _totalArray.count; i ++)
        {
            NSData *imageData = [[_totalArray objectAtIndex:i] valueForKey:@"postdata"];
            NSData *orignImageData = [[_totalArray objectAtIndex:i] valueForKey:@"source"];
            NSString *IDString = [[_totalArray objectAtIndex:i] valueForKey:@"connectid"];
            
            NSString *imageString = [imageData base64EncodedStringWithOptions:0];
            NSString *orignImageString = [orignImageData base64EncodedStringWithOptions:0];
            //
            if ([IDString isEqualToString:@"0"])
            {
                
            }
            else
            {
                orignImageString = @"";
            }
            
            NSDictionary *diction = @{@"imageContent":imageString,
                                      @"origImageContent":orignImageString,
                                      @"contents":@[],
                                      @"material_id":IDString};
            
            [array addObject:diction];
            
        }
        
        [dic setValue:stringID forKey:@"starId"];
        [dic setValue:titleString forKey:@"title"];
        [dic setValue:[NSString stringWithFormat:@"%d", reEditeInt] forKey:@"canRefactor"];
        
        [dic setValue:array forKey:@"images"];
        
//        NSLog(@"%@", dic);
        [WuLiUpLoadImageRequest UpLoadImage:dic];

    }
    
    
    
}



- (void)fabuCenggongGetBack:(NSNotification *)notion
{
    [hudView removeFromSuperview];
    
    NSDictionary *dic = [notion userInfo];
    if ([[dic valueForKey:@"success"] intValue] == 1)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
